package com.gt.deceive.utils;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * 时间zj
 */
public class CreateTimeUtil {

    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            String s = "2018-11-04 18:00:00";
            String e = "2018-11-04 19:00:00";
            List<Long> l = randomDate(s, e,50);
            for(Long lon : l){
                System.out.println(sdf.format(lon));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据时间区间随机生成时间（开始时间和结束时间在同一天)
     * @param beginDate     开始时间 eg:2018-11-04 18:00:00
     * @param endDate       结束时间 eg:2018-11-04 19:00:00
     * @param randNum       生成数量 eg:20
     * @return
     */
    public static List<Long> randomDate(String beginDate, String endDate, int randNum) {
        List<Long> list = new ArrayList<Long>();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start = format.parse(beginDate);// 构造开始日期
            Date end = format.parse(endDate);// 构造结束日期
            // getTime()表示返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
            if (start.getTime() >= end.getTime()) {
                return null;
            }
            for(int i=0;i<randNum;i++){
                long date = random(start.getTime(), end.getTime());
                list.add(date);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    private static long random(long begin, long end) {
        Long rtn = null;
        try {
            rtn = testRandom_generatingLongBounded_withRange(begin, end);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rtn;
    }

    public static long testRandom_generatingLongBounded_withRange(long min, long max) throws Exception {
        long rangeLong = min + (((long) (new Random().nextDouble() * (max - min))));
        return rangeLong;
    }

    public static void update(long time){
        String url = "jdbc:mysql://192.168.40.231:3306/zj?useUnicode=true&characterEncoding=UTF8";
        String user = "root";
        String password = "123";
        try {
            Connection conn = JDBCUtil.getConnection4Mysql(url,user, password);
            String sql = "insert into zj_time (time) values (?)";
            PreparedStatement pstmt;
            System.out.println(sql);
            pstmt = conn.prepareStatement(sql);
            pstmt.setLong(1, time);
            pstmt.executeUpdate();
            pstmt.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
